package com.lizheng.yunservice.utils;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaCodeLineColor;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.stereotype.Component;

import java.io.File;

@Slf4j
@Component
@RequiredArgsConstructor
public class WxUtils {

    private final WxMaService wxMaService;

    /**
     * 获取openid
     *
     * @param code code
     * @return {@code String}
     */
    public String getSessionInfo(String code) {
        String openid = "";
        try {
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
            openid = session.getOpenid();
            // TODO 可以增加自己的逻辑，关联业务相关数据
            // 清理ThreadLocal
            WxMaConfigHolder.remove();
        } catch (WxErrorException e) {
        } finally {
            WxMaConfigHolder.remove();
        }
        return openid;
    }

    /**
     * 获取手机号信息
     *
     * @param code 手机号的code
     * @return {@code String}
     */
    public String getPhoneNoInfo(String code) {
        String phoneNumber = "";
        try {
            WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(code);
            phoneNumber = phoneNoInfo.getPhoneNumber();
            // TODO 可以增加自己的逻辑，关联业务相关数据
            // 清理ThreadLocal
            WxMaConfigHolder.remove();
        } catch (WxErrorException e) {
        } finally {
            WxMaConfigHolder.remove();
        }
        return phoneNumber;
    }

    /**
     * 获取小程序码
     */
    public void createWxaCodeUnlimit() {
        try {
            WxMaCodeLineColor lineColor = new WxMaCodeLineColor();
            File file = wxMaService.getQrcodeService().createWxaCodeUnlimit("1", "", false, "release", 430, false,
                    lineColor, false);
            // 获取文件的绝对路径
            String filePath = file.getAbsolutePath();
            System.out.println("文件路径： " + filePath);
            // TODO 可以增加自己的逻辑，关联业务相关数据
            // 清理ThreadLocal
            WxMaConfigHolder.remove();
        } catch (WxErrorException e) {
        } finally {
            WxMaConfigHolder.remove();
        }
    }

}

